let http = require('http')
let https = require('https')
let url = require('url')
const cheerio = require('cheerio');


const server = http.createServer()

server.on('request', (req, res) => {
    const urlObj = url.parse(req.url, true)
    res.writeHead(200, {
        //键值对
        //跨域
        "content-type": "application/json;charset=utf-8",
        "access-control-allow-origin": "*"//允许跨域（所有）
    })

    if (urlObj.pathname === '/api/getInfo') {
        //做和爬虫有关的事情
        //参数传一个匿名异步函数，用来做爬虫
        httpget(data => res.end(spider(data)))

    } else {
        res.end('404')
    }
})

//https://i.maoyan.com/
function httpget(cb) {
    let data = ''
    https.get('https://i.maoyan.com/#movie', (res) => {
        res.on('data', (chunk) => {
            data += chunk
        })//不断监听data的内容，拿到chunk数据片段

        res.on('end', () => {  //监听到最后，处理完数据
            cd(data)
        })
    })
}
//爬虫的函数
function spider(data) {
    const $ = cheerio.load(data);
    let $movieslist = $('.column.content')
    let movies = []
    $movieslist.each((index, value) => {
        movies.push({
            title: $(value).find('.title').text(),
            grade: $(value).find('.grade').text(),
            actor: $(value).find('.actor').text(),
        })
    })
    console.log(movies);
    return JSON.stringify(movies);

}

server.listen(80, () => {
    console.log('http://127.0.0.1')
})